#! /bin/sh

# 参考文章
# https://blog.csdn.net/qq_36881106/article/details/82623271
# http://www.west.cn/docs/51562.html

# 拷贝脚本的时候运行的时候如果报错，应该是文件格式转换的问题
# bash: ./a.sh: /bin/bash^M: bad interpreter: No such file or directory
# yum -y install dos2unix
# dos2unix labeld.sh

# 第一次运行的时候获取一下超级管理员权限
# chmod +x labeld.sh

BASE_HOME=/cicro/proj/label/java
LOG_HOME=/cicro/proj/label/log
SERVER_PORT=8080
APP_NAME=label.jar
PROFILES_ACTIVE=prod
JAVA_OPTS="-Xms512m -Xmx512m -XX:PermSize=64m -XX:MaxPermSize=128m"

# set customer varibales
# ulimit -n 65535
# export JAVA_HOME=/usr/java/jdk1.8.0_172
# export JAVA_OPTS="-Xms1024m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=128m"

log () {
    echo "========>> $1 <<========"
}

get_pid_by_port () {
    PID=$(netstat -anp | grep $1 | grep LISTEN | awk '{printf $7}' | cut -d/ -f1)

    if [[ "$PID" != "" && "${PID:0:1}" != "-" ]] ; then
        echo $PID
    else
        echo -1
    fi
}

get_status () {
	PID=$(get_pid_by_port $1)
	
	if [[ "$PID" != "" && "${PID:0:1}" != "-" ]] ; then
		echo "${APP_NAME} is running. pid is [$PID]"
	else
		echo "${APP_NAME} is NOT running."
	fi
}

kill_by_port () {
    PID=$(get_pid_by_port $1)

    echo "[$1] pid: [$PID]"

    if [ "$PID" != "-1" ] ; then
        kill -9 $PID
    fi
}

case "$1" in
    'start' )
        log "label start ..."
        nohup java $JAVA_OPTS -jar $BASE_HOME/$APP_NAME > $LOG_HOME/catalina.out 2>&1 --spring.profiles.active=$PROFILES_ACTIVE &
        log "label start ok."
        ;;
    'stop' )
        log "label stop ..."
        kill_by_port $SERVER_PORT
        sleep 1s
        log "label stop ok."
        ;;
    'restart' )
        $0 stop
        sleep 1s
        $0 start
        ;;
	'status' )
        get_status $SERVER_PORT
        ;;	
    'cc' )
        > $LOG_HOME/catalina.out
        exit 1
        ;;
    'tc' )
        tail -f $LOG_HOME/catalina.out
        exit 1
        ;;
    'vc' )
        vim $LOG_HOME/catalina.out
        exit 1
        ;;
    * )
        echo "Usage: $0 [ start | stop | restart | status | cc | tc | vc ]"
        exit 1
        ;;
esac
